package project.mail;

import org.json.JSONException;
import org.json.JSONObject;
import project.Dao.UserDao;
import project.Entity.Code;
import project.Entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static java.lang.System.out;


public class MailSender extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了doGet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了doPost");
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了login");
        try {
            process(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //验证码
    public  String codeGenerator(Integer length) {
        char[] charArray = new char[length];
        short start = (short)'0';   //0的ASCII码是48
        short end = (short)'z';    //z的ASCII码是122（0到z之间有特殊字符）
        for (int i = 0; i < length; i++) {
            while(true)
            {
                char cc1 = (char)((Math.random()*(end-start))+start);
                if(Character.isLetterOrDigit(cc1))  //判断字符是否是数字或者字母
                {
                    charArray[i] = cc1;
                    break;
                }
            }
        }
        String StringRes = new String(charArray);//把字符数组转化为字符串
        return StringRes;
    }


    protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, Exception,JSONException {

        String mail_address = request.getParameter("email");
        String action = request.getParameter("action");
        request.setCharacterEncoding("UTF-8");
        out.println("注册邮箱:" + mail_address + "\n指令:" + action);
        JSONObject json = new JSONObject();

        switch (action){
            case "forget_get_code":
            {
                UserDao userDao = new UserDao();
                List<User> list = userDao.getUserByEmail(mail_address);
                if(list.size()==0){
                    json.put("result", 0);
                    json.put("reason", "该邮箱未注册！");
                    break;
                }
                String code = codeGenerator(6);

                String verificationCode = "<p style=\"color: red\">"+code+"</p>";
                Mail mail = new Mail(mail_address, verificationCode);
                mail.verificationCode = verificationCode;
                mail.receiveMailAccount = mail_address;
                mail.forWhat = "找回密码";
                mail.send();

                if(!userDao.queryTempCode(mail_address).isEmpty()){
                    userDao.updateTempCode(mail_address, code);
                }
                else userDao.saveTempCode(mail_address, code);
                json.put("result", 1);
                break;
            }
            case "forget_commit_code":
            {
                UserDao userDao = new UserDao();
                List<Code> list = userDao.queryTempCode(mail_address);
                if (list.isEmpty()){
                    json.put("result", 0);
                    json.put("reason", "验证码已失效！");
                    break;
                }
                List<User> list1 = userDao.getUserByEmail(mail_address);
                if(list1.size()==0){
                    json.put("result", 0);
                    json.put("reason", "该邮箱未注册！");
                    break;
                }
                String password = request.getParameter("password");
                String code = request.getParameter("code");
                if(list.get(0).email.equals(mail_address) && list.get(0).code.equals(code)){
                    User user = new User(list1.get(0).getEmail(), password, list1.get(0).getName(), list1.get(0).getUrl(), list1.get(0).getTime());
                    if (userDao.updateUser(user)){
                        json.put("result", 1);
                        userDao.deleteTempCode(mail_address);
                    }
                    else {
                        json.put("result", 0);
                        json.put("reason", "插入数据库出错！");
                    }
                }
                else {
                    json.put("result", 0);
                    json.put("reason", "验证码错误！");
                }
                break;
            }
            case "register_get_code":
            {
                UserDao userDao = new UserDao();
                List<User> list = userDao.getUserByEmail(mail_address);
                if(list.size()==1){
                    json.put("result", 0);
                    json.put("reason", "该邮箱已注册！");
                }
                else {
                    String code = codeGenerator(6);

                    String verificationCode = "<p style=\"color: red\">"+code+"</p>";
                    Mail mail = new Mail(mail_address, verificationCode);
                    mail.verificationCode = verificationCode;
                    mail.receiveMailAccount = mail_address;
                    mail.forWhat = "注册账号";
                    mail.send();

                    if(!userDao.queryTempCode(mail_address).isEmpty()){
                        userDao.updateTempCode(mail_address, code);
                    }
                    else userDao.saveTempCode(mail_address, code);
                    json.put("result", 1);
                }
                break;
            }


            case "register_commit_code":
            {
                UserDao userDao = new UserDao();
                List<Code> list = userDao.queryTempCode(mail_address);
                if (list.isEmpty()){
                    json.put("result", 0);
                    json.put("reason", "验证码已失效！");
                }
                else {
                    String password = request.getParameter("password");
                    String register_time = request.getParameter("register_time");
                    String name = codeGenerator(4);
                    String profile_url = "";
                    String code = request.getParameter("code");

                    if(list.get(0).email.equals(mail_address) && list.get(0).code.equals(code)){
                        User user = new User(mail_address, password, name, profile_url, register_time);
                        if (userDao.addUser(user)){
                            json.put("result", 1);
                            userDao.deleteTempCode(mail_address);
                        }
                        else {
                            json.put("result", 0);
                            json.put("reason", "插入数据库出错！");
                        }
                    }
                    else {
                        json.put("result", 0);
                        json.put("reason", "验证码错误！");
                    }

                }
                break;
            }

        }
        ////查看数据库


        out.println(json);
        //将响应消息返回页面
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();


    }
}
